<template>
	<page-loading :show="showPage">
		<view class="flex flex-dir-c flex-ai-c main">
			<view class="already-existing flex flex-ai-c flex-jc-sb" style="width: 700rpx;" v-if="cardList">
				<view class="flex flex-ai-c flex-jc-c" @click="goPage(0)">
					<image class="icon" src="https://files.yzsheng.com/client/imgs/vip.png"></image>
					<view>
						{{ cardList.formatText }}，剩余
						<text>{{ cardList.surplus }}</text>
						{{ cardList.unit }}
					</view>
					<view class="icon-arrow"><u-icon name="play-right-fill" color="#666" size="18"></u-icon></view>
				</view>
				<view style="color: #999999;" class="flex flex-ai-c">
					<view style="margin-right: 15rpx;">重新扫码</view>
					<view @click="onScan"><i-icon icon="iconsaoyisao" type="single" size="40rpx" color="#999999"></i-icon></view>
				</view>
			</view>
			<view v-show="mycarlist.length !== 0" @click="goPage">
				<view class="top flex flex-ai-c" v-for="(item, index) in mycarlist" :key="item.id">
					<view class="top-main flex">
						<view class="flex">
							<view class="top-logo"><image style="width:90rpx;height: 90rpx;" :src="'https://files.yzsheng.com/goodimg/brandimg/' + item.brand_Id + '.png'"></image></view>
							<view class="top-title">
								<view>{{ item.brand_Name }}-{{ item.car_Type_Name }}</view>
								<view class="pz">{{ item.car_Name }}</view>
							</view>
						</view>
					</view>
					<view style="margin:0 20rpx;"><u-icon name="arrow-right" size="32rpx" color="#999999"></u-icon></view>
					<!-- <view class="flex flex-jc-fe" style="flex: 1;position: absolute;top: 30rpx;right: 24rpx;">
						<text class="maintain" @click="goBy(index)" >保养记录</text>
					</view> -->
				</view>
			</view>
			<view v-show="mycarlist.length === 0" class="top flex flex-jc-c flex-dir-c default" style="height: 160rpx;position: relative;">
				<view style="margin: 0 42rpx;">
					<image
						src="https://files.yzsheng.com/client/index/carMaintenance/tianjiaqiche.png"
						style="width: 199rpx;height: 91rpx;position: absolute;bottom: 33rpx;right: 40rpx;"
					></image>
					<view style="color: #666666;">添加爱车，提供精准适配服务</view>
					<view class="add" @click="addConf">
						添加爱车
						<u-icon name="arrow-right"></u-icon>
					</view>
				</view>
			</view>
			<view class="content">
				<!-- 会员信息 -->
				<!-- <view class="flex flex-jc-c flex-ai-c info" v-if="cardList">
    			<view class="icon" v-if="current !== 0" @click="onChangeCard('prev')">
    				<u-icon name="play-left-fill" size="22" color="#999999"></u-icon>
    			</view>
    			<view>{{cardList.formatText}}，剩余<text>{{cardList.surplus}}</text>{{cardList.unit}}</view>
    			<view class="icon" v-if="current <= changeList.length - 2" @click="onChangeCard('next')">
    				<u-icon name="play-right-fill" size="22" color="#999999"></u-icon>
    			</view>
    		</view> -->
				<view class="num" style="font-size: 34rpx;">欢迎光临 祝您洗车愉快</view>
				<!-- 地址 -->
				<view class="flex flex-ai-c flex-jc-c address" v-if="station">
					<view style="margin-right: 20rpx;"><u-icon name="map-fill" size="34"></u-icon></view>
					<view>
						<view>{{ station.selfServiceCarWashStationResponse.station_Name }}</view>
						<!-- <view>{{station.selfServiceCarWashMachineResponse.wash_Machine_Id}}</view> -->
						<view>{{ id }}</view>
					</view>
				</view>
			</view>

			<view class="num">您的999位邻居都在用</view>

			<!-- btn -->
			<view style="position: fixed;bottom: 40rpx;">
				<!-- <view>
					<view class="flex flex-jc-sb">
						<u-checkbox-group shape="circle" active-color="#F30000">
							<u-checkbox v-model="item.checked" v-for="(item, index) in list"
								:key="index" :name="item.name">{{item.name}}</u-checkbox>
						</u-checkbox-group>
						<view>￥20.00</view>
					</view>
				</view>
				<view style="font-size: 22rpx;color: #999999;margin-bottom: 30rpx;">代洗车服务包含，代客机器洗车，车身擦拭收水、内饰清洗擦拭</view>
				<view class="btn flex flex-jc-c flex-ai-c" @click="goPay" v-if="list[0].checked">
					<view>去支付</view>
				</view> -->
				<view style="width: 640rpx;" class="btn flex flex-jc-c flex-ai-c" @click="goWash">
					<view>{{ id ? '知道了，继续洗车' : '知道了，去洗车' }}</view>
				</view>
			</view>

			<!-- 会员卡选择 -->
			<u-popup mode="bottom" v-model="isShow">
				<view v-for="(item, index) in changeList" :key="index">
					<view class="flex flex-ai-c" style="line-height: 100rpx;" @click="choose(item)">
						<view>{{ item.coupon_Name }}</view>
						<view style="margin: 0 20rpx;">{{ item.actually_Money }}元</view>
						<view>{{ item.pay_Platform_Name }}</view>
					</view>
				</view>
			</u-popup>
			<u-modal
				v-model="confirmShow"
				@confirm="confirm"
				@cancel="cancel"
				:show-cancel-button="true"
				ref="uModal"
				confirm-text="更换卡券"
				cancel-text="购买卡券"
				content="你当前卡券余额不足，如有其它卡券，请选择更换，或者购买卡券"
			></u-modal>
			<u-mask :show="firstchange" @click="show = false">
				<view class="wid100">
					<view class="cardlistwarp">
						<view class="width-100 pad10 border-bottom-1">
							<view class="pad-t-b-20 u-text-center font-32">请选择可用卡券</view>
							<view class="heigh300">
							<u-radio-group v-model="firstchangeIndex" @change="radioGroupChange" active-color="#FBD220">
								<u-radio class="width-100" style="flex-flow: row-reverse;" v-for="(it, index) in allActiveCardList" :key="index" :name="index">
									<view class="width160 font-28">
										{{ it.formatText }}，剩余
										<text>{{ it.surplus }}</text>
										{{ it.unit }}
									</view>
								</u-radio>
							</u-radio-group>
							</view>
						</view>
						<view class="width-100 u-text-center pad-t-b-20" style="color: #0076FF;" @click="chooseCard">确认</view>
					</view>
					<view class="x">
						<u-icon name="close-circle" color="#fff" size="26px" @click="goback"></u-icon></view>
				</view>
			</u-mask>
			<!-- 			<u-popup v-model="firstchange" mode="center" width="60%" border-radius="10" class="chooseCard">
		
			</u-popup> -->
		</view>
	</page-loading>
</template>

<script>
import { getUrlParam } from '@/utils/common-api.js';
const dayjs = require('@/utils/dayjs.js');
export default {
	data() {
		return {
			isPay: null, //是否支付
			list: [
				{
					id: 0,
					name: '代洗服务',
					checked: false
				}
			],
			mycarlist: [],
			isShow: false,
			id: '', // 0线上 1扫码
			pageIndex: 1,
			cardList: null,
			changeList: [],
			showPage: false,
			station: null, // 站点信息
			current: 0, // 当前会员索引
			isLogin: uni.getStorageSync('token') || false,
			cardId: '',
			//添加爱车列表
			specifAll: {
				brandlist: [], //品牌
				Serieslist: [], //系列
				Displacement: [], //排量
				Modelyear: [], //年款
				Configulist: [] //车子
			},
			confirmShow: false, //余额不足提示模态框状态
			MyActiveCardList: [],
			firstTime: true,
			firstchange: false, //首次选择会员卡
			allActiveCardList: [], //所有可选会员卡数组
			firstchangeIndex: 0
		};
	},
	onLoad(op) {
		this.cardId = op.cardId || '';
		this.isPay = op.state || null;
		if (this.isPay) {
			this.list[0].checked = true;
		}
		if (op.id) {
			this.id = op.id || '';
		} else {
			let resObj = getUrlParam(decodeURIComponent(op.q));
			this.id = resObj.id;
		}
		// 选择品牌，系列，排量，年款，车子
		uni.$on('carMaintenances', data => {
			Object.assign(this.specifAll, data);
			if (data.licenseplate && data.pageFrom === 'carMaintenances') {
				//添加爱车
				this.AddCar();
			}
		});
		if (uni.getStorageSync('token')) {
			this.$nextTick(() => {
				this.getPageData();
				this.GetCarList();
			});
		} else {
			uni.setStorage({
				key: 'launchFlag',
				data: false
			});
			uni.setStorageSync('existingOrder', this.id);
			uni.navigateTo({
				url: '/pages_logins/login/login?mode=selfwash'
			});
		}
	},
	mounted() {
		// this.GetMyFirstCard();
	},
	onShow() {
		console.log(this.cardId, this.id);
		if (!this.firstTime) {
			this.GetCarList();
			// if (!this.showPage && !this.isLogin && uni.getStorageSync('token')) {
			this.getPageData();
		}
		// }
	},
	onHide() {
		console.log('隐藏');
		this.firstTime = false;
	},
	onUnload() {
		console.log('卸载');
	},
	methods: {
		//去支付
		goPay() {
			if (!this.list[0].checked) {
				uni.showToast({
					title: '请勾选代洗服务',
					icon: 'none'
				});
			}
		},
		//我添加爱车
		async AddCar() {
			const value = uni.getStorageSync('Ztc_C_USER_INFO');
			if (value) {
				var ids;
				ids = value.id;
			}
			try {
				//添加爱车重复，退出添加
				this.mycarlist.forEach((item, index) => {
					if (item.car_Id === this.specifAll.Configulist.id) {
						// uni.showToast({
						//   title: '添加重复，请重新选择',
						//   icon: 'none'
						// })
						throw new Error('EndIterative');
					}
				});
				let data = {
					uid: ids,
					brand_Id: this.specifAll.brandlist.bid,
					brand_Name: this.specifAll.brandlist.brand,
					car_Type_Id: this.specifAll.Serieslist.carTypeId,
					car_Type_Name: this.specifAll.Serieslist.carTypeName,
					car_Id: this.specifAll.Configulist.id,
					car_Name: this.specifAll.Configulist.name,
					car_Num: this.specifAll.licenseplate, //车牌号
					mileage: 0, //里程 /km
					vin: '', //vin号
					engine: '', //发动机号
					displacement: this.specifAll.Displacement.pName,
					yeartype: this.specifAll.Modelyear.years
				};
				const res = await this.$api.common.AddCar(data);
				this.mycarlist = res.data.list;
				this.GetCarList();
			} catch (e) {
				if (e.message !== 'EndIterative') throw e;
			}
		},
		onScan() {
			// #ifdef H5
			let res = {
				result: 'https://lineapi.yzsheng.com/pages_commodity?id=wc2400197&type=existingOrder'
			};
			let urlParam = getUrlParam(res.result);
			if (urlParam.type === 'existingOrder') {
				this.$store.commit('purchaseChannel', true);
				uni.redirectTo({
					url: `/pages_commodity/selfWash/existingOrder?id=${urlParam.id}`
				});
			} else {
				uni.showToast({
					icon: 'none',
					title: '二维码有误'
				});
			}
			return false;
			// #endif
			if (uni.getStorageSync('token')) {
				uni.scanCode({
					success: res => {
						this.scanSuccess(res);
					}
				});
			} else {
				uni.navigateTo({
					url: '/pages_logins/login/login?mode=selfwash'
				});
			}
		},
		async scanSuccess(res) {
			try {
				let urlParam = getUrlParam(res.result);
				if (urlParam.type === 'existingOrder') {
					this.$store.commit('purchaseChannel', true);
					uni.redirectTo({
						url: `/pages_commodity/selfWash/existingOrder?id=${urlParam.id}`
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: '二维码有误'
					});
				}
			} catch (e) {
				//TODO handle the exception
			}
		},
		async GetCarList() {
			const value = uni.getStorageSync('Ztc_C_USER_INFO');
			if (value) {
				var ids;
				ids = value.id;
			}
			try {
				let data = {
					pageIndex: 1,
					pageSize: 1,
					uid: ids
				};
				const res = await this.$api.commodity.GetCarList(data);
				this.mycarlist = res.data.list.slice(0, 1);
				// console.log(res);
			} catch (e) {}
		},
		goPage(type) {
			let mobile = uni.getStorageSync('Ztc_C_USER_INFO').mobile;
			if (type === 0) {
				uni.navigateTo({
					url: `/pages_userModule/myCoupon/index?status=1&type=choose&id=${this.id}&mobile=${mobile}`
				});
			} else {
				uni.navigateTo({
					url: '/pages_commodity/myLoveCar/myLoveCar'
				});
			}
		},
		getPageData() {
			this.getMyInProgressOrder(() => {
				let arr = [this.GetMyActiveCardList()];
				if (this.id) {
					arr.push(this.getSelfServiceCarWashMachineInfo());
				}
				Promise.all(arr).then(data => {
					console.log('会员卡id', this.cardId);
					if (data[0].code === 200) {
						//判断是否有会员卡

						if (data[0].data.list.length > 0) {
							if (this.firstTime) {
								this.allActiveCardList = data[0].data.list;
								this.firstchange = true;
							} else {
								if (this.cardId) {
									let e = data[0].data.list.find(v => this.cardId === v.id);
									this.cardList = e;
								} else {
									this.cardList = data[0].data.list[0];
								}
							}

							// console.log(this.cardList)
							// if (!this.cardList.isAvailable) {
							// 	this.confirmShow = true;
							// }
						} else {
							uni.redirectTo({
								url: `/pages_commodity/selfWash/buyMember?machineId=${this.id}`
							});
						}
					}
					if (data.length > 1 && data[1].code === 200) {
						this.station = data[1].data;
					}
					this.showPage = true;
				});
			});
		},
		// 获取当前人正在进行中的洗车订单
		async getMyInProgressOrder(callback) {
			try {
				const res = await this.$api.selfServiceCarWash.GetMyInProgressOrder();
				if (res.code === 200 && res.data) {
					let { self_Service_Car_Wash_Card_Order_Id, wash_Machine_Id } = res.data.selfServiceCarWashOrder;
					uni.redirectTo({
						url: `/pages_commodity/selfWash/index?cardId=${self_Service_Car_Wash_Card_Order_Id}&machineId=${wash_Machine_Id}`
					});
				} else {
					callback && callback();
				}
			} catch (e) {
				callback && callback();
			}
		},
		// 获取洗车机相关信息
		getSelfServiceCarWashMachineInfo(callback) {
			return new Promise(async (resolve, reject) => {
				try {
					const res = await this.$api.selfServiceCarWash.GetSelfServiceCarWashMachineInfo({
						wash_Machine_Id: this.id
					});
					resolve(res);
				} catch (e) {
					//TODO handle the exception
				}
			});
		},
		// 获取可用优惠卡
		async GetMyFirstCard() {
			try {
				const res = await this.$api.selfServiceCarWash.GetMyFirstCard();
				if (res.code === 200) {
					if (res.data) {
						let item = res.data;
						item.day = dayjs(item.deadline).diff(dayjs(), 'day') + 1;
						const start = Date.parse(new Date());
						if (item.card_Type === 1) {
							const end = Date.parse(item.deadline);
							//当前时间和结束时间
							if (start > end) {
								item.day = 0;
							}
							item.formatText = '月卡会员';
							item.surplus = `${item.day}`;
							item.unit = '天';
						} else if (item.card_Type === 2) {
							item.formatText = '次卡会员';
							item.surplus = `${item.left_Times}`;
							item.unit = '次';
						} else if (item.card_Type === 3) {
							item.left_Seconds = Math.floor(item.left_Seconds / 60);
							item.formatText = '计时会员';
							item.surplus = `${item.left_Seconds}`;
							item.unit = '分';
						} else if (item.card_Type === 4) {
							item.formatText = '充值会员';
							item.surplus = `${item.card_Left_Cost}`;
							item.unit = '元';
						}
						this.cardList = item;
					} else {
						uni.redirectTo({
							url: `/pages_commodity/selfWash/buyMember?machineId=${this.id}`
						});
					}
					// res.data.list.map(item => {
				} else {
					// resolve(res);
				}
			} catch (e) {
				//TODO handle the exception
			}
		},
		//会员卡列表
		GetMyActiveCardList() {
			return new Promise(async (resolve, reject) => {
				try {
					let data = {
						pageIndex: this.pageIndex,
						pageSize: 100
					};
					const res = await this.$api.selfServiceCarWash.GetMyActiveCardList(data);
					if (res.code === 200) {
						res.data.list.map(item => {
							// let item=res.data
							item.day = dayjs(item.deadline).diff(dayjs(), 'day') + 1;
							const start = Date.parse(new Date());
							if (item.card_Type === 1) {
								const end = Date.parse(item.deadline);
								//当前时间和结束时间
								if (start > end) {
									item.day = 0;
								}
								item.formatText = '月卡会员';
								item.surplus = `${item.day}`;
								item.unit = '天';
							} else if (item.card_Type === 2) {
								item.formatText = '次卡会员';
								item.surplus = `${item.left_Times}`;
								item.unit = '次';
							} else if (item.card_Type === 3) {
								item.left_Seconds = Math.floor(item.left_Seconds / 60);
								item.formatText = '计时会员';
								item.surplus = `${item.left_Seconds}`;
								item.unit = '分';
							} else if (item.card_Type === 4) {
								item.formatText = '充值会员';
								item.surplus = `${item.card_Left_Cost}`;
								item.unit = '元';
							}
						});
						// res.data=item
						resolve(res);
						// this.MyActiveCardList=res.data.list
					} else {
						resolve(res);
					}
				} catch (e) {
					//TODO handle the exception
				}
			});
		},
		onChangeCard(type) {
			if (type === 'next') {
				this.current = this.current + 1;
			} else {
				this.current = this.current - 1;
			}
			this.cardList = this.changeList[this.current];
		},
		goWash() {
			if (this.cardList) {
				console.log(this.id);
				if (this.id) {
					uni.redirectTo({
						url: `/pages_commodity/selfWash/index?cardId=${this.cardList.id}&machineId=${this.id}`
					});
				} else {
					uni.redirectTo({
						url: `/pages_commodity/selfWash/map`
					});
				}
			} else {
				uni.navigateTo({
					url: `/pages_commodity/selfWash/buyMember?machineId=${this.id}`
				});
			}
		},
		addConf() {
			let token = uni.getStorageSync('token');
			if (!token) {
				this.$u.toast('请登录！');
				this.$u.debounce(this.login, 1000);
			} else {
				uni.navigateTo({
					url: '/pages_common/addYourCar/addYourCar?type=120' + '&pageFrom=carMaintenances'
				});
			}
		},
		confirm() {
			// console.log('更换')
			let mobile = uni.getStorageSync('Ztc_C_USER_INFO').mobile;
			uni.navigateTo({
				url: `/pages_userModule/myCoupon/index?status=1&type=choose&id=${this.id}&mobile=${mobile}`
			});
		},
		cancel() {
			uni.navigateTo({
				url: '/pages_commodity/selfWash/buyMember'
			});
		},
		// 选择会员卡
		radioGroupChange(e) {
			console.log(e);
			this.firstchangeIndex = e;
		},
		// 选择会员卡
		chooseCard() {
			this.cardList = this.allActiveCardList[this.firstchangeIndex];
			this.firstchange = false;
		},
		goback(){
			console.log('点击了')
			this.firstchange=false
			// uni.redirectTo({
			//     url: '/pages_commodity/selfWash/selfWash'
			// });
			uni.navigateBack({
				delta:1
			})
		}
	}
};
</script>

<style lang="scss" scoped>
.top {
	position: relative;
	width: 700rpx;
	// height: 200rpx;
	padding: 42rpx 0rpx;
	background: #ffffff;
	box-shadow: 0px 0px 10rpx 0px rgba(0, 0, 0, 0.12);
	border-radius: 10rpx;
	margin: 20rpx auto 0 auto;

	.top-main {
		flex: 1;
	}

	.top-title {
		// width: 319rpx;
		margin-left: 35rpx;
		font-size: 28rpx;
		font-weight: 500;
		color: #666666;

		.pz {
			display: -webkit-box;
			overflow: hidden;
			white-space: normal !important;
			text-overflow: ellipsis;
			word-wrap: break-word;
			-webkit-line-clamp: 1;
			-webkit-box-orient: vertical;
		}

		view:first-child {
			font-size: 34rpx;
			display: -webkit-box;
			overflow: hidden;
			white-space: normal !important;
			text-overflow: ellipsis;
			word-wrap: break-word;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
			font-weight: bold;
			color: #333333;
		}
	}

	.maintain {
		color: #3d3d3d;
		font-weight: 500;
		width: 163rpx;
		height: 54rpx;
		background: linear-gradient(0deg, #fbd220, #ffe23e);
		border-radius: 27rpx;
		text-align: center;
		line-height: 54rpx;
	}

	.top-logo {
		margin-left: 25rpx;
		width: 90rpx;
		height: 90rpx;
	}
}

.already-existing {
	height: 78rpx;
	background-color: #fff;
	padding: 0 30rpx;
	color: #333333;
	font-size: 26rpx;
	color: #333;

	.icon {
		width: 38rpx;
		height: 38rpx;
		margin-right: 15rpx;
		margin-top: -4px;
	}

	.icon-arrow {
		margin-left: 24rpx;
		margin-top: -1px;
	}
}

.main {
	.icon {
		margin: 0 10rpx;
	}

	.content {
		margin: 144rpx 0;
	}

	.info {
		font-size: 28rpx;
		line-height: 100%;
	}

	.address {
		// position: relative;
		// top: 50rpx;
		margin-top: 50rpx;
		font-size: 24rpx;
		color: #666666;
	}

	.num {
		font-size: 40rpx;
		color: #333333;
		font-weight: bold;
	}

	text {
		font-size: 26rpx;
		font-weight: bold;
		color: #333333;
		padding: 0 10rpx;
	}

	.btn {
		// width: 640rpx;
		width: 100%;
		height: 88rpx;
		// background: linear-gradient(0deg, #FDD421, #FFE23E);
		background: #4a4c59;
		border-radius: 44rpx;
		font-size: 30rpx;
		color: #ffffff;
	}
}

.add {
	width: 200rpx;
	height: 60rpx;
	background: linear-gradient(0deg, #fbd220, #ffe23e);
	border-radius: 30px;
	font-size: 28rpx;
	font-weight: bold;
	color: #3d3d3d;
	text-align: center;
	line-height: 60rpx;
	margin-top: 20rpx;
}
.wid100 {
	width: 100%;
	height: 100%;
	.cardlistwarp {
		width: 60%;
		padding: 10rpx;
		border-radius: 10rpx;
		margin: 70% auto 20%;
		background: #fff;
	}
	.pad10 {
		padding: 20rpx;
	}
	.width160 {
		width: 320rpx;
	}
	.x {
		text-align: center;
		// position: absolute;
		// bottom: -20rpx;
	}
}
.heigh300{
	height: 200rpx;
	overflow-y: scroll;
}
</style>
